<script setup>
// 采购分析
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'

const fetchProcurementData = async () => {
	try {
		const response = await fetch('http://localhost/api/ads-procurement')
		const data = await response.json()
		chartOption.value.xAxis[0].data = data.map(d => d.statisticDate)
		chartOption.value.series[0].data = data.map(d => d.totalProcurement)
		chartOption.value.series[1].data = data.map(d => d.completionRate)
	} catch (error) {
		console.error('采购数据获取失败:', error)
	}
}

onMounted(fetchProcurementData)
const chartOption = ref({
	backgroundColor: 'transparent', // 透明背景以适配深色主题
	tooltip: {
		trigger: 'axis',
		axisPointer: {
			type: 'cross',
			crossStyle: {
				color: '#999',
			},
		},
		valueFormatter: function (value) {
			if (value > 10000) {
				return (value / 10000).toFixed(2) + '万'
			}
			return value + '%'
		},
	},
	legend: {
		top: '10%',
		data: ['采购量', '采购完成率'],
	},
	grid: {
		top: '20%',
		left: '9%',
		right: '7%',
		bottom: '15%',
	},
	xAxis: [
		{
			type: 'category',
			data: [],
			axisPointer: {
				type: 'shadow',
			},
		},
	],
	yAxis: [
		{
			type: 'value',
			name: '采购量（万）',
			splitNumber: 3,
			min: 0,
			axisLabel: {
				formatter: function (value) {
					return (value / 10000).toFixed(0)
				},
			},
		},
		{
			type: 'value',
			splitNumber: 3,
			name: '完成率',
			min: 80,
			max: 100,
			axisLabel: {
				formatter: '{value}%',
			},
		},
	],
	series: [
		{
			name: '采购量',
			type: 'bar',
			barWidth: 26,
			itemStyle: {
				normal: {
					barBorderRadius: [5, 5, 0, 0],
					color: new echarts.graphic.LinearGradient(
						0,
						1,
						0,
						0,
						[
							{
								offset: 0,
								color: '#4033F9',
							},
							{
								offset: 0.8,
								color: '#BA97F9',
							},
						],
						false
					),
					shadowColor: 'rgba(0, 0, 0, 0.1)',
				},
			},
			data: [],
		},
		{
			name: '采购完成率',
			type: 'line',
			yAxisIndex: 1,
			symbol: 'rect',
			symbolSize: 5,
			symbolColor: 'white',
			lineStyle: { normal: { width: 2, color: '#da2f78' } },
			itemStyle: { normal: { color: 'white' } },
			areaStyle: {
				normal: {
					color: new echarts.graphic.LinearGradient(
						0,
						0,
						0,
						1,
						[
							{
								offset: 0,
								color: 'rgba(230, 48, 123, 0.8)',
							},
							{
								offset: 0.8,
								color: 'rgba(230, 48, 123, 0)',
							},
						],
						false
					),
					shadowColor: 'rgba(0, 0, 0, 0.1)',
					shadowBlur: 10,
				},
			},
			// itemStyle: {
			//     borderWidth: 3,
			//     borderColor: '#EE6666',
			//     color: 'yellow'
			//   },

			data: [' '],
		},
	],
})
</script>

<template>
	<v-chart theme="chalk" :option="chartOption" />
</template>

<style scoped></style>
